/*!
	@file
	@author		George Evmenov
	@date		07/2009
*/

#include "MyGUI_EggVertexBuffer.h"
#include "MyGUI_VertexData.h"
#include "MyGUI_EggDiagnostic.h"

namespace MyGUI{

	const size_t VERTEX_IN_QUAD = 6;
	const size_t RENDER_ITEM_STEEP_REALLOCK = 5 * VERTEX_IN_QUAD;

	EggVertexBuffer::EggVertexBuffer() :
		mNeedVertexCount(0),
		mVertexCount(RENDER_ITEM_STEEP_REALLOCK),
        mSizeInBytes(0)
	{
	}

	EggVertexBuffer::~EggVertexBuffer()
	{
		destroy();
	}

	void EggVertexBuffer::setVertexCount(size_t _count)
	{
		if (_count != mNeedVertexCount)
		{
			mNeedVertexCount = _count;
			destroy();
			create();
		}
	}

	size_t EggVertexBuffer::getVertexCount()
	{
		return mNeedVertexCount;
	}

	Vertex* EggVertexBuffer::lock(){
        Vertex* pBuffer=reinterpret_cast<Vertex*>(mEggVertexBuffer->_lock(egg::BA_WRITE));
		return pBuffer;
	}

	void EggVertexBuffer::unlock(){
        mEggVertexBuffer->_unlock();
	}

	void EggVertexBuffer::destroy(){
	}

	void EggVertexBuffer::create(){
        using namespace egg;
		mSizeInBytes = mNeedVertexCount * sizeof(MyGUI::Vertex);
		void* data = 0;
        VertexFormat vf;
        size_t offset = 0;
        vf.addDeclare(VA_POSITION,sizeof(Vertex),offset);
        offset += (sizeof(float) * 3);
        vf.addDeclare(VA_COLOR0,sizeof(Vertex),offset);
        offset += (4);
        vf.addDeclare(VA_TEXCOORD0,sizeof(Vertex),offset);
        mEggGeometry=GeometryPtr(new Geometry());
        mEggVertexBuffer=VertexBufferPtr(new VertexBuffer(vf,mNeedVertexCount,BU_STREAM,data));
        mEggGeometry->attachVertexBuffer("position",mEggVertexBuffer);
	}

} // namespace MyGUI
